<template>
  <div class="msg-box">
    <div class="msg-top">
      <Dialogbox
      v-for="(item,index) in chatItems"
      :key="index"
      :message="item.message"
      :from="item.from"></Dialogbox>
    </div>
    <div class="msg-down">
      <el-input
        resize="none"
        class="text-box"
        type="textarea"
        :rows="4"
        placeholder="请输入你想问的问题"
        v-model="textarea">
      </el-input>
      <button class="send-btn" @click="send" >send</button>
    </div>
  </div>
</template>

<script>
import Dialogbox from '@/components/Dialogbox.vue'

export default {
  name: 'Robot',
  data () {
    return {
      textarea: '',
      chatItems: [
        {
          message: '',
          from: 2
        }
      ],
      username: ''
    }
  },
  methods: {
    scrollToBtn: function () {
      this.$nextTick(() => {
        var div = document.querySelector('.msg-top')
        div.scrollTop = div.scrollHeight
      })
    },
    send () {
      if (this.textarea !== '') {
        const newmsg = {
          message: '',
          from: 1
        }
        newmsg.message = this.textarea

        this.chatItems.push(newmsg)
        this.$axios.post('http://localhost:9000/', {
          data: {
            user: this.username,
            msg: this.textarea
          }
        }).then(res => {
          const data = res.data
          const robotresponse = {
            message: '',
            from: 2
          }
          robotresponse.message = data
          this.chatItems.push(robotresponse)
        }, err => {
          this.$message.error('网络异常，请稍后再试')
          console.log(err)
        })
        this.textarea = ''
      }
    }
  },
  components: {
    Dialogbox
  },
  updated () {
    this.scrollToBtn()
  },
  created () {
    var token = JSON.parse(window.localStorage.getItem('token'))
    this.chatItems[0].message = token + '你好，我是你的智能医疗小助手。'
    this.username = token
  }
}
</script>

<style scoped>
.msg-box{
  position: relative;
  width: 100%;
  height: 100%;
}
.msg-top {
  position: absolute;
  bottom: 20%;
  left: 0;
  overflow-y:scroll;
  width: 100%;
  height: 77%;
  padding: 3% 0 0 0;
  background: rgb(238, 238, 238);
}
.msg-down{
  position: absolute;
  left: 0;
  bottom: 0;
  height: 20%;
  width: 100%;
}
.text-box{
  width: 80%;
  position: absolute;
  left: 3%;
  top: 10%;
}
.send-btn{
  color: black;
  font-weight: bold;
  width: 60px;
  height: 50px;
  background: white;
  border-radius: 25px;
  position: absolute;
  left: 87%;
  top: 30%;
  cursor: pointer;
}
.send-btn:hover{
  /* background: #89c4ff; */
  background: #409EFF;
  color: white;
  border: none;
}
</style>
